<template>
    <van-nav-bar title="搜索" left-text="返回" left-arrow @click-left="back" />

    <!-- 显示加载中 -->
    <Loading v-show="loading" />

    <!-- 菜单搜索 -->
    <van-search v-model="searchValue" shape="round" input-align="center" placeholder="搜索菜谱"
        @search="search(searchValue)" v-if="!loading" />

    <!-- 结果提示语 -->
    <h2 class="promt" v-show="promt.length > 0 && !loading">{{ promt }}</h2>

    <!-- 结果列表 -->
    <div class="result" v-show="!loading">
        <van-cell is-link v-for="{ id, name, highlights } in results" @click="go(id)">
            <template #title>
                <van-highlight :keywords="highlights" :source-string="name" />
            </template>
        </van-cell>
    </div>

</template>

<script setup lang="ts">
import req from '@/utils/requests'
import Loading from '@/components/Loading.vue'
import { useSearchStore } from '@/stores/search.ts'

const loading = ref(true)

const router = useRouter()

const searchStore = useSearchStore()
const searchValue = computed({
    get: () => searchStore.value,
    set: (val: string) => searchStore.setValue(val)
})
const results = ref([])

const promt = computed(() => {
    if (searchValue.value.length == 0) {
        return ""
    }
    return `搜索到与“${searchValue.value}”相关的${results.value.length}个结果`
})

watch(promt, () => {
    if (promt.value.length == 0) {
        results.value = []
    }
})

const back = () => {
    router.back()
}

const go = (cookId: number) => {
    router.push(`/detail/${cookId}`)
}

const search = async (value: string): Promise<void> => {
    console.log(`开始搜索: ${value}`)
    loading.value = true
    try {
        results.value = await req.post('/api/search', {
            value: value,
            page: 1,
            num: 10
        })
    } catch (e: any) {
        console.log("搜索异常");
        results.value = []
    } finally {
        loading.value = false
        searchValue.value = value
    }
}

onMounted(async () => {
    const v: string = searchStore.value
    console.log(`搜索菜谱: ${v}`)
    search(v)
})


</script>

<style scoped>
.promt {
    display: block;
    columns: var(--van-step-circle-color);
    text-align: center;
    font-size: small;
}

.result {
    --van-highlight-tag-color: red;
}
</style>